<template>
  <div
    id="carForms"
  >
    <v-title title="汽车报表"></v-title>
    <el-row>
      <el-col :xs="24" :sm="24" :lg="24">
        <div id="reportrange" class="form-control">
          <div class="block">
            <el-row class="bgColor">
              <el-col :xs="24" :sm="24" :lg="24">
                <div class="item">
                  <label for="cascader">事业部:</label>
                  <el-cascader
                    clearable
                    placeholder="请选择"
                    :options="deptOptions"
                    filterable
                    :show-all-levels="false"
                    :collapse-tags="true"
                    v-model="dept"
                    @change="deptSearch"
                    :props="props"
                    style="margin-left: 10px; width:12%"
                    id="cascader"
                    >
                  </el-cascader>
                </div>
              </el-col>
              <el-col :xs="24" :sm="24" :lg="24" style="margin-top: -24px;margin-left: 62%">
                <label for="select" style="margin-right: 20px">技术中心/产品中心:</label>
                <el-select
                  v-model="Produnction"
                  multiple
                  @change="tecSearch"
                  placeholder="请选择"
                  collapse-tags
                  clearable
                  filterable
                  style="width: 150px;margin-top: -70px;margin-right: 34%;">
                  <el-option
                    v-for="item in ProdunctionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :xs="24" :sm="24" :lg="24" style="margin-top: -24px;margin-left: 22%">
                <label for="select" style="margin-right: 20px">项目状态:</label>
                <el-select
                  v-model="proStatus"
                  multiple
                  @change="proStatusSearch"
                  placeholder="请选择"
                  collapse-tags
                  clearable
                  filterable
                  style="width: 150px;margin-top: -70px;margin-right: 34%;">
                  <el-option
                    v-for="item in ProStatusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-col>
              
            </el-row>
            <el-row >
              <el-col :xs="24" :sm="24" :lg="24" style="margin-top: 25px">
                <label for="select" style="margin-right: 20px">资源分类:</label>
                <el-select
                  v-model="recourse"
                  @change="recourseSearch"
                  placeholder="请选择"
                  collapse-tags
                  clearable
                  filterable  
                  style="width: 150px;margin-top: -70px;margin-right: 34%;width:12%">
                  <el-option
                    v-for="item in recourseOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-col>
               <el-col :xs="24" :sm="24" :lg="24" style="margin-top: -25px;margin-left: 30%;">
                <label for="select" style="margin-right: 20px">客户:</label>
                <el-select
                  v-model="cusDept"
                  multiple
                  @change="cusDeptSearch"
                  placeholder="请选择"
                  collapse-tags
                  clearable
                  filterable
                  style="width: 350px;margin-top: -70px;margin-right: 34%;">
                  <el-option
                    v-for="item in cusDeptOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :xs="24" :sm="24" :lg="24" style="margin-top: 28px">
                <label for="select" style="margin-right: 20px">技术领域:</label>
                <el-cascader
                  style="width: 150px;"
                  placeholder="请选择"
                  :options="tecAreaOptions"
                  :props="props"
                  @change="tecAreaSearch"
                  collapse-tags
                  clearable
                  filterable
                  ref="tree"></el-cascader>
              </el-col>
              <el-col :xs="24" :sm="24" :lg="24" style="margin-top:-35px">
                <label for="select" style="margin-right: 20px;margin-left: 30%">时间段:</label>
                 <el-date-picker
                  v-model="value1"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="changeDateRange">
                </el-date-picker>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
      <el-button type="primary" plain round style="float: right; margin: 10px 0 10px 0;" @click="down()">导出</el-button>
    </el-row>
    <el-card class="box-card">
      <el-table 
      :data="tableData"
       border 
       style="width: 90%" 
       max-height="700"  
       v-loading="loading" 
       element-loading-text="拼命加载中" 
       element-loading-spinner="el-icon-loading" 
       show-summary 
       :summary-method="getSummaries"
       >
        <el-table-column prop="project_name" label="项目" width="200" align="center" fixed="left">
        </el-table-column>
        <el-table-column label="资源分类" width="180" align="center" fixed="left">
          <template slot-scope="scope"> 
            <div v-if="tab==='0'">
              <div class="borders" v-if="scope.row.type[0].label==='need'"  >{{ "需求" }}</div>
              <div class="borders1" v-if="scope.row.type[1].label==='get'" >{{ "供给" }}</div>
              <div class="borders2" v-if="scope.row.type[2].label==='gap'" >{{ "GAP"  }}</div>
            </div>

            <div v-else>
              <div v-show="tab==='1'">
                <div v-if="scope.row.type[0].label==='need'">{{ "需求" }}</div>
              </div>

              <div v-show="tab==='2'">
                <div v-if="scope.row.type[1].label==='get'">{{ "供给" }}</div>
              </div>

              <div v-show="tab==='3'">
                <div v-if="scope.row.type[2].label==='gap'">{{ "GAP" }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="汇总" width="180" align="center" type="cell">
          <template slot-scope="scope">
            <div v-if="tab==='0'">
              <div class="borders" v-if="scope.row.type[0].sum_value">{{ scope.row.type[0].sum_value.toFixed(2) }}</div>
              <div class="borders" v-else>{{ scope.row.type[0].sum_value }}</div>
           
              <div class="borders1" v-if="scope.row.type[1].sum_value">{{ scope.row.type[1].sum_value.toFixed(2) }}</div>
              <div class="borders1" v-else>{{ scope.row.type[1].sum_value }}</div>
           
              <div class="borders2" v-if="scope.row.type[2].sum_value">{{ scope.row.type[2].sum_value.toFixed(2) }}</div>
              <div class="borders2" v-else>{{ scope.row.type[2].sum_value }}</div>
            </div>
            <div v-else>
              <div v-show="tab==='1'">
                <div v-if="scope.row.type[0].sum_value">{{ scope.row.type[0].sum_value.toFixed(2) }}</div>
                <div v-else>{{ scope.row.type[0].sum_value }}</div>
              </div>

              <div v-show="tab==='2'">
                <div v-if="scope.row.type[1].sum_value">{{ scope.row.type[1].sum_value.toFixed(2) }}</div>
                <div v-else>{{ scope.row.type[1].sum_value }}</div>
              </div>

              <div v-show="tab==='3'">
                <div v-if="scope.row.type[2].sum_value">{{ scope.row.type[2].sum_value.toFixed(2) }}</div>
                <div v-else>{{ scope.row.type[2].sum_value }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="v" v-for="(v,i) in monthRange"  :label="v+'月'" width="180" align="center" :key="i" type="cell">
          <template slot-scope="scope">
            <div v-if="tab==='0'">
              <div class="borders" v-if="scope.row.type[0].sum_value">{{ scope.row.type[0].value[v].toFixed(2) }}</div>
              <div class="borders" v-else>{{ scope.row.type[0].value[v]}}</div>
           
              <div class="borders1" v-if="scope.row.type[1].sum_value">{{ scope.row.type[1].value[v].toFixed(2) }}</div>
              <div class="borders1" v-else>{{ scope.row.type[1].value[v]}}</div>
            
              <div class="borders2" v-if="scope.row.type[2].sum_value">{{ scope.row.type[2].value[v].toFixed(2) }}</div>
              <div class="borders2" v-else>{{ scope.row.type[2].value[v]}}</div>
            </div>

            <div v-else>
              <div v-show="tab==='1'">
                <div v-if="scope.row.type[0].sum_value">{{ scope.row.type[0].value[v].toFixed(2) }}</div>
                <div v-else>{{ scope.row.type[0].value[v]}}</div>
              </div>

              <div v-show="tab==='2'">
               <div v-if="scope.row.type[1].sum_value">{{ scope.row.type[1].value[v].toFixed(2) }}</div>
               <div v-else>{{ scope.row.type[1].value[v]}}</div>
              </div>

              <div v-show="tab==='3'">
                <div v-if="scope.row.type[2].sum_value">{{ scope.row.type[2].sum_value.toFixed(2) }}</div>
                <div v-else>{{ scope.row.type[2].sum_value }}</div>
              </div>
            </div>

            <!-- <div v-show="isShow">
              <div class="borders" v-if="scope.row.type[0].sum_value">{{ scope.row.type[0].value[v].toFixed(2) }}</div>
              <div class="borders" v-else>{{ scope.row.type[0].value[v]}}</div>
            </div>
            <div v-show="isShow1">
              <div class="borders1" v-if="scope.row.type[1].sum_value">{{ scope.row.type[1].value[v].toFixed(2) }}</div>
              <div class="borders1" v-else>{{ scope.row.type[1].value[v]}}</div>
            </div>
            <div v-show="isShow2">
              <div class="borders2" v-if="scope.row.type[2].sum_value">{{ scope.row.type[2].value[v].toFixed(2) }}</div>
              <div class="borders2" v-else>{{ scope.row.type[2].value[v]}}</div>
            </div> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        class="marT"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="baseSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        style="margin-top:10px;margin-left:34%"
        >
      </el-pagination> -->
    </el-card>
  </div>
</template>

<script>
import { getHeaderName } from '@/app.config'
import VTitle from '@/views/sys/internetThings/title';

export default {
  name: 'carForms',
  components: {
    VTitle,
  },
  data() {
    return {
      // loading2: false,
      tab:'0',
      isShow:true,
      isShow1:true,
      isShow2:true,
      value1:'',
      tecAreaOptions:[],
      tecArea:'',
      cusDeptOptions:[],
      cusDept:'',
      recourseOptions:[    // "需求""供给""GAP"
        {
          value:"需求",
          label:"需求"
        },
        {
          value:"供给",
          label:"供给"
        },
        {
          value:"GAP",
          label:"GAP"
        }
      ],
      recourse:'',
      ProStatusOption:[],
      proStatus:'',
      // loading1:false,
      Produnction:'',
      ProdunctionOptions:[],
      props: { multiple: true },
      deptOptions:[],
      dept:'',
      paramsData:{},
      current:1,
      baseSize:10,
      total:0,
      monthRange:[],
      tableData:[],
      value2:'',
      loading:false
    };
  },
  created(){
  },
  mounted(){
    this.getTableData()
    this.getDeptOptions()
    this.getProStatusOption()
    this.getCusDept()
    this.getTecAreaOptions()
  },
  watch:{
  },
  methods: {
    down(){
       this.loading = true
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/car_project/data_to_excel',
          method: "get",
          headers: getHeaderName(),
          responseType: 'blob',
        }).then(res => {
          if(res.status === 200) {
            this.loading = false
            const blob = new Blob([res.data]);
            const fileName = '资源报表.xlsx';
            // for IE
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
              // for Non-IE (chrome, firefox etc.)
              const elink = document.createElement('a');
              elink.download = fileName;
              elink.style.display = 'none';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
              this.loading = false
              this.$message({
              type:"success",
              message:"导出成功!"
            })
          }
          } else {
            this.loading = false
            this.$message.error('下载出错了!'); 
          }
        }).catch(err => {
            this.$message.error('下载出错了!'); 
            this.loading = false
        })
    },
    getSummaries(param) {
      const { columns, data } = param;
      // console.log(9,columns)
      const sums = [];
      //循环处理所有列数据
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }else if(index === 1){
          if(this.tab==="0"){
            var word1 = <div class="borders">{'总需求'}</div>
            var word2 = <div class="borders1">{'总实际'}</div>
            var word3 = <div class="borders2">{'总GAP'}</div>
            sums[index] = [word1,word2,word3];
          }if(this.tab==="1"){
            var word11 = <div>{'总需求'}</div>
            sums[index] = [word11];
          }if(this.tab==="2"){
            var word11 = <div>{'总实际'}</div>
            sums[index] = [word11];
          }if(this.tab==="3"){
            var word11 = <div>{'总GAP'}</div>
            sums[index] = [word11];
          }
          
          return;
        }
        //将每列的所有数据数字化处理成一个数组
        const values1 = data.map(item => {
          if(column.type == 'cell') {
            let obj = item.type[0].value
            if(index === 2){
              obj = item.type[0].sum_value
            }
             let spendTime1
             spendTime1 = obj[column.property]
             return spendTime1
          } else {
             return NaN
          }
        });
       
        const values2 = data.map(item => {
          if(column.type == 'cell') {
            let obj = item.type[1].value
            let spendTime2 = 0
            spendTime2 = obj[column.property]
             return spendTime2
          } else {
             return NaN
          }
        });

        const values3 = data.map(item => {
            if(column.type == 'cell') {
              let obj = item.type[0].sum_value
              let spendTime3 = 0
              spendTime3 = obj
              return spendTime3
            } else {
              return NaN
            }
          });

          const values4 = data.map(item => {
          if(column.type == 'cell') {
            let obj = item.type[1].sum_value
            let spendTime4 = 0
            spendTime4 = obj
            return spendTime4
          } else {
            return NaN
          }
        });
        if (!values1.every(value => isNaN(value))) {
          var num1 = values1.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0);
          var num2 = values2.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0);
          if(this.tab==="0"){
            var html1 = <div class="borders">{num1}</div>
            var html2 = <div class="borders1">{num2}</div>
            var html3 = <div class="borders2">{(num1-num2).toFixed(2)}</div>
            sums[index] = [html1,html2,html3]
          }if(this.tab==="1"){
            var word33 = <div>{num1}</div>
            sums[index] = [word33];
          }if(this.tab==="2"){
             var word33 = <div>{num2}</div>
            sums[index] = [word33];
          }if(this.tab==="3"){
             var word33 = <div>{(num3-num4).toFixed(2)}</div>
            sums[index] = [(num1-num2).toFixed(2)];
          }
         
        }
        else{
          var num3 = values3.reduce((prev, curr) => {
            const val = Number(curr);
            if (!isNaN(val)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0);
          var num4 = values4.reduce((prev, curr) => {
            const val = Number(curr);
            if (!isNaN(val)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0);
          if(this.tab==="0"){
            var html4 = <div class="borders">{num3}</div>
            var html5 = <div class="borders1">{num4}</div>
            var html6 = <div class="borders2">{(num3-num4).toFixed(2)}</div>
            sums[index] = [html4,html5,html6] 
          }if(this.tab==="1"){
            var word44 = <div>{num3}</div>
            sums[index] = [word44];
          }if(this.tab==="2"){
             var word44 = <div>{num4}</div>
            sums[index] = [word44];
          }if(this.tab==="3"){
             var word44 = <div>{(num3-num4).toFixed(2)}</div>
            sums[index] = [word44];
          }
        }
      });
      return sums;
    },
    changeDateRange(e){
      let arr = []
      let arr1 = []
      let startData = e[0]
      let endData = e[1]
      var YY1 = startData.getFullYear() 
      var MM1 = (startData.getMonth() + 1 < 10 ? '0' + (startData.getMonth() + 1) : startData.getMonth() + 1) ;
      arr.push(YY1 , MM1)
      arr = arr.map(v=>{
        if (v[0] == "0") {
          return (v = v.slice(1));
        } else {
          return v;
        }
      })
      let startTime = arr.join("-")

      var YY2 = endData.getFullYear() 
      var MM2 = (endData.getMonth() + 1 < 10 ? '0' + (endData.getMonth() + 1) : endData.getMonth() + 1) ;
      arr1.push(YY2 , MM2)
      arr1 = arr1.map(v=>{
        if (v[0] == "0") {
          return (v = v.slice(1));
        } else {
          return v;
        }
      })
      let endTime = arr1.join("-")
      console.log(startTime,endTime)
      this.paramsData['start_date'] = startTime
      this.paramsData['end_date'] = endTime
      this.current = 1
      this.getTableData()
    },
    tecAreaSearch(val){
      let tempArr = []
      let tempArr1 = this.$refs.tree.getCheckedNodes()
      tempArr1.map(val => {
        tempArr.push(val.value)
      })
      val.map(item => {
        tempArr.push(item[item.length-1])
      })
      tempArr=Array.from(new Set(tempArr))
      this.paramsData['technical_field_ids'] = tempArr
      this.current = 1
      this.getTableData()
    },
    getTecAreaOptions() {
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/filter/technical_field/tree',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.tecAreaOptions = res.data.data
      })
    },
    cusDeptSearch(val){
      this.paramsData["kh_zh"] = val
      this.current = 1
      this.getTableData()
    },
    getCusDept(){
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/car_project/kh_zh_tree_list',
          method: "get",
          headers: getHeaderName(),
        }).then(res => {
          if(res.data.code === 200) {
            this.cusDeptOptions = res.data.data
          }
        })
    },
    recourseSearch(e){
      console.log(111,e)
      // e.map(v =>{
        // console.log(v)
        if(e==="需求"){
          this.tab = '1'
          // console.log(this.tab,'需求')
        }
        if(e==="供给"){
          this.tab = '2'
          // console.log(this.tab,"供给")
        }
        if(e==="GAP"){
          this.tab = '3'
          // console.log(this.tab,"GAP")
        }
      // })
      
    },
    proStatusSearch(val){
      this.paramsData["status"] = val
      this.current = 1
      this.getTableData()
    },
    getProStatusOption(){
       this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/car_project/status_tree_list',
          method: "get",
          headers: getHeaderName(),
        }).then((res) => {
          if(res.data.code === 200) {
            this.ProStatusOption = res.data.data
          }
        })
    },
    tecSearch(){},
    getTecOptions(){ },
    getDeptOptions(){
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/car_project/tree_list',
          method: "get",
          headers: getHeaderName(),
        }).then((res) => {
          if(res.data.code === 200) {
            this.deptOptions = res.data.data
          }
        })
    },
    deptSearch(val){
      let praProId = []
      val.map(v => {
        praProId.push(v[1])
      })
      this.paramsData["project_ids"] = praProId
      this.current = 1
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getTableData()
    },
    handleSizeChange(val){
    },
    getTableData(){
       this.loading = true
       this.paramsData["page"] = this.current
       this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/car_project/data',
          method: "post",
          headers: getHeaderName(),
          data:this.paramsData
        }).then((res => {
          if(res.data.code === 200){
            this.loading = false
            this.tableData = res.data.data.data
            this.monthRange = res.data.data.month_range
            this.total = res.data.data.totalCount
          }else{
            this.loading = false
            this.$message.error('请求出错')
          }
        }))
    }
  },
};
</script>

<style lang="scss" scoped>
#carForms {
  label {
    color: rgb(103, 106, 108);
    font-weight: normal;
  };
  .form-control {
    background-color: #ffffff;
    background-image: none;
    border: 1px solid #e5e6e7;
    border-radius: 1px;
    color: inherit;
    display: block;
    padding: 6px 12px;
    transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
    width: 100%;
    font-size: 0.9rem;
    box-shadow: none;
    margin-bottom: 10px
  };
  .borders{
    border-bottom: 1px solid #c5c4c1;
    height: 25px;
    width: 183px;
    margin-left: -14px;
    margin-top:10px;
    // margin-bottom:10px;
  };
  .borders1{
    border-bottom: 1px solid #c5c4c1;
    height: 32px;
    width: 183px;
    margin-left: -14px;
    margin-top:10px;
    // margin-bottom:10px;
  };
  .borders2{
    // border-bottom: 1px solid #c5c4c1;
    height: 25px;
    width: 183px;
    margin-left: -14px;
    margin-top:10px;
    // margin-bottom:10px;
  };
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
  //   .btn-group {
  //     position: relative;
  //     .edit {
  //       position: absolute;
  //       top: 50%;
  //       right: -2%;
  //       transform: translate(-50%, -50%);
  //     }
  //   }
}
</style>